import React, { useState, useEffect } from 'react';
import service from '../utils/axios';
import dayjs from 'dayjs';

interface Operation {
  id: number;
  title: string;
  type: '促销' | '活动' | '优惠券' | '会员活动';
  status: '进行中' | '已结束' | '未开始';
  startDate: string;
  endDate: string;
  budget: number;
  roi: number;
  description: string;
}

interface Task {
  id: number;
  title: string;
  assignee: string;
  deadline: string;
  status: '待处理' | '进行中' | '已完成' | '延期';
  priority: '高' | '中' | '低';
}

interface PushMessage {
  id: number;
  content: string;
  type: '通知' | '活动' | '优惠';
  target: string;
  time: string;
  status: '成功' | '失败' | '待推送' | '已推送';
}

interface Rusers {
  content: string
  typeA: string
  typeB: string
  typeC: string
  time: string
  code: number
  __v: number
  _id: string
}

type PushType = '通知' | '活动' | '优惠';
type PushTimeType = 'now' | 'schedule';

const Operations: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'campaigns' | 'tasks' | 'planning' | 'Push Notification'>('campaigns');
  const [showPushForm, setShowPushForm] = useState(false);
  const [pushContent, setPushContent] = useState('');
  const [pushType, setPushType] = useState<PushType>('通知');
  const [pushTarget, setPushTarget] = useState('');
  const [pushTimeType, setPushTimeType] = useState<PushTimeType>('now');
  const [pushScheduleTime, setPushScheduleTime] = useState('');

  const [socket, setSocket] = useState<WebSocket | null>(null);
  const ws = new WebSocket(`ws://localhost:3000`)

  // 推送历史数据
  const [pushHistory, setPushHistory] = useState<PushMessage[]>([
    { id: 1, content: '618购物节活动即将开始，全场最低5折起！', type: '活动', target: '全部用户', time: '2023-06-15 10:00', status: '已推送' },
    { id: 2, content: '会员日特惠，每月会员专享折扣和福利！', type: '通知', target: '部分用户', time: '2023-07-01 09:00', status: '成功' },
    { id: 3, content: '新用户立减50元优惠券已发放，请查收！', type: '优惠', target: '全部用户', time: '2023-06-15 14:00', status: '失败' },
    { id: 4, content: '夏季新品上市，全场包邮！', type: '通知', target: '全部用户', time: '2023-08-01 11:00', status: '待推送' },
  ]);

  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedPush, setSelectedPush] = useState<PushMessage | Rusers | null>(null);


  useEffect(() => {
    // 创建WebSocket连接
    const ws = new WebSocket(`ws://localhost:3000`)

    ws.onopen = () => {
      ws.send(JSON.stringify({ type: 'login' }));
      console.log('连接服务器触发')
      setSocket(ws)
    }

    ws.onmessage = (data) => {
      console.log('服务器被触发了', data)
    }

    ws.onerror = error => {
      console.log('出现了错误，被触发了:', error)
    }

    ws.onclose = () => {
      console.log('关闭服务器时触发')
    }

    // 清理函数 - 在组件卸载时执行
    return () => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.close()
        console.log('WebSocket连接已关闭')
      }
    }
  }, [])

  const handlePushSubmit = () => {
    const newId = pushHistory.length + 1;
    const newMessage: PushMessage = {
      id: newId,
      content: pushContent,
      type: pushType,
      target: pushTarget,
      time: pushTimeType === 'now' ? new Date().toISOString().slice(0, 16) : pushScheduleTime,
      status: '待推送',
    };
    setPushHistory(prev => [...prev, newMessage]);
    setShowPushForm(false);
    setPushContent('');
    setPushType('通知');
    setPushTarget('');
    setPushTimeType('now');
    setPushScheduleTime('');


    socket?.send(JSON.stringify({
      typeA: pushType,
      typeB: pushTarget,
      typeC: pushTimeType,
      time: Date.now(),
      code: 2,
      content: pushContent,
    }));

  };

  // 运营活动数据
  const operations: Operation[] = [
    {
      id: 1,
      title: '618购物节',
      type: '促销',
      status: '已结束',
      startDate: '2023-06-01',
      endDate: '2023-06-18',
      budget: 25000,
      roi: 3.8,
      description: '年中大促销，全场最低5折起'
    },
    {
      id: 2,
      title: '会员日特惠',
      type: '会员活动',
      status: '进行中',
      startDate: '2023-07-01',
      endDate: '2023-07-31',
      budget: 10000,
      roi: 2.5,
      description: '每月会员专享折扣和福利'
    },
    {
      id: 3,
      title: '新用户立减50元',
      type: '优惠券',
      status: '进行中',
      startDate: '2023-06-15',
      endDate: '2023-08-15',
      budget: 15000,
      roi: 1.8,
      description: '新用户首单立减50元'
    },
    {
      id: 4,
      title: '夏季新品上市',
      type: '活动',
      status: '未开始',
      startDate: '2023-08-01',
      endDate: '2023-08-15',
      budget: 18000,
      roi: 0,
      description: '夏季新品上市，全场包邮'
    }
  ];

  // 任务数据
  const tasks: Task[] = [
    {
      id: 1,
      title: '准备7月会员活动物料',
      assignee: '王设计',
      deadline: '2023-06-25',
      status: '已完成',
      priority: '高'
    },
    {
      id: 2,
      title: '更新首页Banner',
      assignee: '李运营',
      deadline: '2023-07-10',
      status: '进行中',
      priority: '中'
    },
    {
      id: 3,
      title: '整理6月活动数据报告',
      assignee: '张分析',
      deadline: '2023-07-05',
      status: '延期',
      priority: '高'
    },
    {
      id: 4,
      title: '设计新用户引导流程',
      assignee: '赵产品',
      deadline: '2023-07-20',
      status: '待处理',
      priority: '中'
    },
    {
      id: 5,
      title: '撰写8月活动方案',
      assignee: '周策划',
      deadline: '2023-07-15',
      status: '进行中',
      priority: '低'
    }
  ];

  const [data, setData] = useState<Rusers[]>([])
  async function getList() {
    const res = await service<Rusers[]>({
      url: '/gk/indexs',
      method: 'GET'
    })
    console.log(res.data)
    setData(res.data)
  }
  useEffect(() => {
    getList()
  }, [])

  return (
    <div className="page-container">
      <h1>运营管理</h1>

      <div className="tabs">
        <button
          className={`tab ${activeTab === 'campaigns' ? 'active' : ''}`}
          onClick={() => setActiveTab('campaigns')}
        >
          活动管理
        </button>
        <button
          className={`tab ${activeTab === 'tasks' ? 'active' : ''}`}
          onClick={() => setActiveTab('tasks')}
        >
          任务管理
        </button>
        <button
          className={`tab ${activeTab === 'planning' ? 'active' : ''}`}
          onClick={() => setActiveTab('planning')}
        >
          运营日历
        </button>
        <button
          className={`tab ${activeTab === 'Push Notification' ? 'active' : ''}`}
          onClick={() => setActiveTab('Push Notification')}
        >
          消息推送
        </button>
      </div>

      {activeTab === 'campaigns' && (
        <div className="tab-content">
          <div className="actions-bar">
            <button className="btn btn-primary">创建活动</button>
            <div className="filter-group">
              <label>活动类型：</label>
              <select>
                <option value="">全部</option>
                <option value="促销">促销</option>
                <option value="活动">活动</option>
                <option value="优惠券">优惠券</option>
                <option value="会员活动">会员活动</option>
              </select>
            </div>
            <div className="filter-group">
              <label>状态：</label>
              <select>
                <option value="">全部</option>
                <option value="进行中">进行中</option>
                <option value="已结束">已结束</option>
                <option value="未开始">未开始</option>
              </select>
            </div>
          </div>
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>活动名称</th>
                  <th>类型</th>
                  <th>状态</th>
                  <th>时间区间</th>
                  <th>预算</th>
                  <th>ROI</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {operations.map(operation => (
                  <tr key={operation.id}>
                    <td>{operation.id}</td>
                    <td>{operation.title}</td>
                    <td>{operation.type}</td>
                    <td>
                      <span className={`status-badge ${operation.status === '进行中' ? 'success' :
                          operation.status === '未开始' ? 'info' :
                            'inactive'
                        }`}>
                        {operation.status}
                      </span>
                    </td>
                    <td>{operation.startDate} 至 {operation.endDate}</td>
                    <td>¥{operation.budget.toLocaleString()}</td>
                    <td>{operation.roi ? operation.roi.toFixed(1) + 'x' : '-'}</td>
                    <td>
                      <button className="btn btn-view">查看</button>
                      <button className="btn btn-edit">编辑</button>
                      {operation.status === '进行中' && (
                        <button className="btn btn-end">结束</button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="summary-cards">
            <div className="summary-card">
              <h3>活动总数</h3>
              <div className="summary-value">{operations.length}</div>
            </div>
            <div className="summary-card">
              <h3>进行中</h3>
              <div className="summary-value">{operations.filter(op => op.status === '进行中').length}</div>
            </div>
            <div className="summary-card">
              <h3>总预算</h3>
              <div className="summary-value">¥{operations.reduce((sum, op) => sum + op.budget, 0).toLocaleString()}</div>
            </div>
            <div className="summary-card">
              <h3>平均ROI</h3>
              <div className="summary-value">
                {(operations.filter(op => op.roi > 0).reduce((sum, op) => sum + op.roi, 0) /
                  operations.filter(op => op.roi > 0).length).toFixed(1)}x
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'tasks' && (
        <div className="tab-content">
          <div className="actions-bar">
            <button className="btn btn-primary">添加任务</button>
            <div className="filter-group">
              <label>状态：</label>
              <select>
                <option value="">全部</option>
                <option value="待处理">待处理</option>
                <option value="进行中">进行中</option>
                <option value="已完成">已完成</option>
                <option value="延期">延期</option>
              </select>
            </div>
            <div className="filter-group">
              <label>优先级：</label>
              <select>
                <option value="">全部</option>
                <option value="高">高</option>
                <option value="中">中</option>
                <option value="低">低</option>
              </select>
            </div>
          </div>
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>任务名称</th>
                  <th>负责人</th>
                  <th>截止日期</th>
                  <th>状态</th>
                  <th>优先级</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {tasks.map(task => (
                  <tr key={task.id}>
                    <td>{task.id}</td>
                    <td>{task.title}</td>
                    <td>{task.assignee}</td>
                    <td>{task.deadline}</td>
                    <td>
                      <span className={`status-badge ${task.status === '已完成' ? 'success' :
                          task.status === '进行中' ? 'info' :
                            task.status === '延期' ? 'error' :
                              'warning'
                        }`}>
                        {task.status}
                      </span>
                    </td>
                    <td>
                      <span className={`priority-badge priority-${task.priority === '高' ? 'high' :
                          task.priority === '中' ? 'medium' :
                            'low'
                        }`}>
                        {task.priority}
                      </span>
                    </td>
                    <td>
                      <button className="btn btn-edit">编辑</button>
                      {task.status !== '已完成' && (
                        <button className="btn btn-complete">完成</button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeTab === 'planning' && (
        <div className="tab-content">
          <div className="calendar-controls">
            <div className="month-selector">
              <button className="btn btn-arrow">◀</button>
              <h3>2023年7月</h3>
              <button className="btn btn-arrow">▶</button>
            </div>
            <button className="btn btn-primary">添加事件</button>
          </div>
          <div className="calendar-container">
            <div className="calendar-header">
              <div className="weekday">周一</div>
              <div className="weekday">周二</div>
              <div className="weekday">周三</div>
              <div className="weekday">周四</div>
              <div className="weekday">周五</div>
              <div className="weekday weekend">周六</div>
              <div className="weekday weekend">周日</div>
            </div>
            <div className="calendar-grid">
              {/* 日历单元格，模拟7月份的部分数据 */}
              {Array.from({ length: 31 }, (_, i) => {
                const day = i + 1;
                const isWeekend = (day + 5) % 7 === 0 || (day + 5) % 7 === 1; // 简单计算周末

                return (
                  <div key={day} className={`calendar-day ${isWeekend ? 'weekend' : ''}`}>
                    <div className="day-number">{day}</div>

                    {/* 示例事件 */}
                    {day === 1 && (
                      <div className="calendar-event member-event">会员日活动开始</div>
                    )}
                    {day === 5 && (
                      <div className="calendar-event report-event">6月数据分析</div>
                    )}
                    {day === 10 && (
                      <div className="calendar-event update-event">更新首页Banner</div>
                    )}
                    {day === 15 && (
                      <div className="calendar-event planning-event">8月活动方案</div>
                    )}
                    {day === 20 && (
                      <div className="calendar-event design-event">用户引导流程</div>
                    )}
                    {day === 25 && (
                      <div className="calendar-event meeting-event">月度复盘会议</div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {activeTab === 'Push Notification' && (
        <div className="tab-content">
          <div className="actions-bar">
            <button className="btn btn-primary" onClick={() => setShowPushForm(true)}>新建推送</button>
          </div>

          {/* 新建推送表单（弹窗/内联） */}
          {showPushForm && (
            <div className="push-form-modal">
              <div className="push-form">
                <h3>新建消息推送</h3>
                <div className="form-group">
                  <label>推送内容：</label>
                  <textarea value={pushContent} onChange={e => setPushContent(e.target.value)} />
                </div>
                <div className="form-group">
                  <label>推送类型：</label>
                  <select value={pushType} onChange={e => setPushType(e.target.value as PushType)}>
                    <option value="通知">通知</option>
                    <option value="活动">活动</option>
                    <option value="优惠">优惠</option>
                  </select>
                </div>
                <div className="form-group">
                  <label>目标用户：</label>
                  <input type="text" value={pushTarget} onChange={e => setPushTarget(e.target.value)} placeholder="全部/部分用户" />
                </div>
                <div className="form-actions">
                  <button className="btn btn-primary" onClick={handlePushSubmit}>提交</button>
                  <button className="btn btn-cancel" onClick={() => setShowPushForm(false)}>取消</button>
                </div>
              </div>
            </div>
          )}

          {/* 推送历史表格 */}
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>内容</th>
                  <th>类型</th>
                  <th>目标用户</th>
                  <th>推送时间</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {
                  data.map(item => (
                    <tr key={item._id}>
                      <td>{item._id}</td>
                      <td>{item.content.length > 10 ? item.content.slice(0, 10) + '...' : item.content}</td>
                      <td>{item.typeA}</td>
                      <td>{item.typeB}用户</td>
                      <td>{dayjs(item.time).format('YYYY-MM-DD HH:mm')}</td>
                      <td>
                        { item.code === 0? '成功':'' }
                        { item.code === 1? '失败':'' }
                        { item.code === 2? '待推送':'' }
                      </td>
                      <td>
                        <button className="btn btn-view" onClick={() => { setSelectedPush(item); setShowDetailModal(true); }}>详情</button>
                        {/* {msg.status === '失败' && <button className="btn btn-edit">重推</button>} */}
                        <button className={item.code === 1?"btn btn-edit":'none'}>重推</button>
                        <button className={item.code === 2?"btn btn-edit":'none'}>推送</button>
                      </td>
                    </tr>
                  ))
                }
              </tbody>
            </table>
          </div>

          {/* 详情弹窗 */}
          {showDetailModal && selectedPush && (
            <div className="modal-overlay" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.35)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, animation: 'fadeIn 0.2s' }}>
              <div className="modal-content" style={{ background: '#fff', borderRadius: 16, padding: '32px 36px', minWidth: 340, maxWidth: 420, boxShadow: '0 8px 32px rgba(0,0,0,0.18)', position: 'relative', fontFamily: 'inherit', animation: 'popIn 0.25s' }}>
                <button style={{ position: 'absolute', top: 18, right: 18, background: 'none', border: 'none', fontSize: 22, cursor: 'pointer', color: '#888' }} onClick={() => { setShowDetailModal(false); setSelectedPush(null); }} title="关闭">×</button>
                <h2 style={{ marginBottom: 10, fontWeight: 700, fontSize: 22, color: '#333', textAlign: 'center', letterSpacing: 1 }}>推送详情</h2>
                <hr style={{ margin: '10px 0 18px 0', border: 'none', borderTop: '1.5px solid #f0f0f0' }} />
                {/* 判断 selectedPush 类型，优先渲染 Rusers 字段 */}
                {'_id' in selectedPush ? (
                  <>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>推送编号</span>
                      <span style={{ fontWeight: 500, color: '#222' }}>{selectedPush._id}</span>
                    </div>
                    <div style={{ marginBottom: 14 }}>
                      <div style={{ color: '#888', marginBottom: 2 }}>推送内容</div>
                      <div style={{ whiteSpace: 'pre-wrap', background: '#f7f7fa', borderRadius: 6, padding: '10px 12px', color: '#444', fontSize: 15, lineHeight: 1.7, boxShadow: '0 1px 2px rgba(0,0,0,0.03)' }}>{selectedPush.content}</div>
                    </div>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>类型</span>
                      <span style={{ color: '#3b82f6', fontWeight: 500 }}>{selectedPush.typeA}</span>
                    </div>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>目标用户</span>
                      <span style={{ color: '#222' }}>{selectedPush.typeB}用户</span>
                    </div>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>推送时间</span>
                      <span style={{ color: '#222' }}>{dayjs(selectedPush.time).format('YYYY-MM-DD HH:mm')}</span>
                    </div>
                    <div style={{ marginBottom: 18, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>状态</span>
                      <span style={{ color: selectedPush.code === 0 ? '#22c55e' : selectedPush.code === 1 ? '#ef4444' : '#f59e42', fontWeight: 500 }}>
                        {selectedPush.code === 0 ? '成功' : selectedPush.code === 1 ? '失败' : '待推送'}
                      </span>
                    </div>
                  </>
                ) : (
                  <>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>推送编号</span>
                      <span style={{ fontWeight: 500, color: '#222' }}>{selectedPush.id}</span>
                    </div>
                    <div style={{ marginBottom: 14 }}>
                      <div style={{ color: '#888', marginBottom: 2 }}>推送内容</div>
                      <div style={{ whiteSpace: 'pre-wrap', background: '#f7f7fa', borderRadius: 6, padding: '10px 12px', color: '#444', fontSize: 15, lineHeight: 1.7, boxShadow: '0 1px 2px rgba(0,0,0,0.03)' }}>{selectedPush.content}</div>
                    </div>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>类型</span>
                      <span style={{ color: '#3b82f6', fontWeight: 500 }}>{selectedPush.type}</span>
                    </div>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>目标用户</span>
                      <span style={{ color: '#222' }}>{selectedPush.target}</span>
                    </div>
                    <div style={{ marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>推送时间</span>
                      <span style={{ color: '#222' }}>{selectedPush.time}</span>
                    </div>
                    <div style={{ marginBottom: 18, display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: '#888' }}>状态</span>
                      <span style={{ color: selectedPush.status === '成功' ? '#22c55e' : selectedPush.status === '失败' ? '#ef4444' : '#f59e42', fontWeight: 500 }}>{selectedPush.status}</span>
                    </div>
                  </>
                )}
                <div style={{ textAlign: 'center', marginTop: 18 }}>
                  <button className="btn btn-primary" style={{ minWidth: 90, padding: '7px 0', borderRadius: 6, fontWeight: 500, fontSize: 15 }} onClick={() => { setShowDetailModal(false); setSelectedPush(null); }}>关闭</button>
                </div>
                <style>{`
                  @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
                  @keyframes popIn { from { transform: scale(0.95); opacity: 0.7; } to { transform: scale(1); opacity: 1; } }
                `}</style>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default Operations; 